<template>
    <ayjDrawer title="客户积分" width="35%" ref="ayjDrawerRef" :slotFooter="false" @closeFun="handleClose">
        <div class="flex_column container_box" ref="containerBoxRef">
            <div class="points_box" ref="pointsBoxRef">
                <div class="customer_points_top bg_gray flex_between">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div class="select_store flex_row" style="cursor: pointer;">
                                <span class="select_store_span font_black3">日期：</span>
                                <el-select class="select_store_el" style="flex: 1;" v-model="formQuery.t_type"
                                    placeholder="请选择" size="mini" @change="selectHandleChange">
                                    <el-option v-for="item in day_ls" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-col>
                        <el-col :span="1"><el-divider direction="vertical"></el-divider></el-col>
                        <el-col :span="7">
                            <div class="select_store flex_row" style="cursor: pointer;">
                                <span class="select_store_span font_black3">云店：</span>
                                <el-select class="select_store_el" style="flex: 1;" v-model="formQuery.idyun"
                                    placeholder="请选择" size="mini" @change="selectHandleChange">
                                    <el-option v-for="item in yd_ls" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-col>
                        <el-col :span="1"><el-divider direction="vertical"></el-divider></el-col>
                        <el-col :span="7">
                            <div class="select_store flex_row" style="cursor: pointer;">
                                <span class="select_store_span font_black3">类型：</span>
                                <el-select class="select_store_el" style="flex: 1;" v-model="formQuery.ch"
                                    placeholder="请选择" size="mini" @change="selectHandleChange">
                                    <el-option v-for="item in ch_ls" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div class="mt10">
                    <span class="font_size14">可用积分：</span>
                    <span class="font_green font_size18">{{ p_fract || 0 }}</span>
                </div>
            </div>
            <div class="table_box mt5">
                <div class="flex_between mb10" style="align-items: flex-end;">
                    <p class="font_size14" style="line-height:1;"> 积分明细 </p>
                    <div>
                        <el-button type="primary" size="mini" @click="handleClick('add')">添加</el-button>
                        <el-button paln size="mini" @click="handleClick('exchange')">兑换</el-button>
                    </div>
                </div>
                <ayjTable :columns="columns" :data="tableData" :hasMore="hasMore" :loading="loading"
                    :height="dynamicHeight" @load-more="loadMoreData">
                    <template #column-p="{ row }"> 
                        <span :class="row.in_out == '1' ? 'font_green' : 'font_red'"> {{ row.in_out == '1' ? '+' : '-' }}{{ row.p || 0}}</span>
                    </template>
                </ayjTable>
            </div>
        </div>
        <customerPoints ref="customerPointsRef" :getYyInfoData="getYyInfoData" @refresh="selectHandleChange"></customerPoints>
    </ayjDrawer>


</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance, defineProps, defineExpose, watch } from '@vue/composition-api'
import { useDynamicHeight } from '@/hooks/useDynamicHeight'
const { proxy } = getCurrentInstance();

import customerPoints from "@/components/customers/customerPoints.vue"


import config from "@/js/conf/Config.js";
import localStore from "@/js/LocalStore.js";

const maxPnum = 20

const ayjDrawerRef = ref(null)
const containerBoxRef = ref(null)
const pointsBoxRef = ref(null)
const p_fract = ref(0)
const loading = ref(false)
const hasMore = ref(true)


// 使用动态高度 hooks
const { dynamicHeight, updateHeight } = useDynamicHeight({
    containerRef: containerBoxRef,
    subtractRef: pointsBoxRef,
    extraHeight: 90 // 额外的间距
})

const formQuery = ref({
    idyun: "0",  // 云店id
    t_type: "0", // 时间 类型 1 当日 2 当月 3 当季 4 当年 5 自定义
    typeid: "0", // 类型id 0 全部
    ch: "0", // 1 获取 2 兑换 其他全部   默认全部
    pfrom: 0,
    pnum: maxPnum,
})

const columns = ref([
    { 
      title: '序号', 
      prop: 'index', 
      width: '50px', 
      align: 'center',
      render: (row, column, index) => index + 1,
    //   fixed: 'left'
    },
    { title: '云店', prop: 'yun_title',},
    { title: '积分', prop: 'p',slot: true},
    { title: '类型', prop: 'type_title',},
    { title: '详情', prop: 'txt_info',},
  ])
  const tableData = ref([])  

const props = defineProps({
    getYyInfoData: {
        type: Object,
        default: () => ({})
    }
})

watch(() => props.getYyInfoData, (newVal) => {
    console.log("newVal2x2x=", newVal)
    if (newVal.id) {
        pFractFun();
        customFractLsFun();
    }
}, { deep: true})


const yd_ls = ref([])
const day_ls = ref([])
const ch_ls = ref([])

const customerPointsRef = ref(null)
const handleClick = (type) => {
    customerPointsRef.value.open(type)
}

const open = async () => {
    await resetData();
    ayjDrawerRef.value.open();
    if (props.getYyInfoData.id) {
        pFractFun();
        customFractLsFun();
    }
    // 等待抽屉完全打开后更新高度
    setTimeout(() => {
        updateHeight()
    }, 100)
}

const handleClose = () => {
    resetData();
    ayjDrawerRef.value.close();
}

const resetData = () => {
    tableData.value = []
    yd_ls.value = []
    day_ls.value = []
    ch_ls.value = []
    p_fract.value = 0
    loading.value = false
    hasMore.value = true
    formQuery.value.pfrom = 0
    formQuery.value.pnum = maxPnum
}

onMounted(() => { })

const selectHandleChange = async () => {
    await resetData();
    customFractLsFun();
    pFractFun();
}

// 积分明细
const customFractLsFun = async () => {
    if (loading.value || !hasMore.value) return
    loading.value = true

    let cp = await localStore.getCpInfo();
    let param = {
        cpid: cp.id,
        customerid: props.getYyInfoData.id,
        ...formQuery.value
    };
    let res = await proxy.$api({ url: config.custom_fract_ls, data: param }).finally(() => {
        loading.value = false
    });
    if (res.status == 1) {
        // 表格数据
        const ln = res.data?.fract_ls?.length || 0
        if (ln < maxPnum) {
            hasMore.value = false
        } else {
            hasMore.value = true
        }
        tableData.value = [...tableData.value, ...(res.data?.fract_ls || [])]
        yd_ls.value = ([...yd_ls.value, ...(res.data?.yd_ls || [])]).map(item => {
            return {
                ...item,
                value: item.idyun,
                label: item.name
            }
        });
        day_ls.value = ([...day_ls.value, ...(res.data?.day_ls || [])]).map(item => {
            return {
                ...item,
                value: item.id,
                label: item.title
            }
        });
        ch_ls.value = ([...ch_ls.value, ...(res.data?.ch_ls || [])]).map(item => {
            return {
                ...item,
                value: item.id,
                label: item.name
            }
        });
    }
}

const loadMoreData = () => {
    if (loading.value || !hasMore.value) return
    formQuery.value.pfrom += maxPnum
    customFractLsFun();
    loading.value = true
}

// 只获取总分
const pFractFun = async (reset = true) => {
    let url = config.CUSTOM_P_FRACT;
    let cp = await localStore.getCpInfo();
    let param = {
        cpid: cp.id,
        customerid: props.getYyInfoData.id,
        ...formQuery.value
    };
    let res = await proxy.$api({ url: url, data: param });
    if (res.status == 1) {
        p_fract.value = res.data.p_fract || 0;
    }
}


defineExpose({
    open
})
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 10px 0 !important;
}

.customer_points_top {
    padding: 10px;
    border-radius: 6px;
}

.select_store ::v-deep .el-input__inner {
    background-color: #f5f5f5 !important;
    border: none !important;
    color: #333 !important;
    padding-left: 4px !important;
    text-align: left !important;
    // border-bottom: 1px solid #e9dede !important;
    border-radius: 0 !important;
}

.customer_points_top ::v-deep .el-divider--vertical {
    height: 1.5rem !important;
    position: relative;
    left: -10px;
}

.container_box {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.table_box {
    flex: 1;
}
</style>
